var $;
layui.config({
    base: '/static/layui/module/'
}).extend({
    eleTree: "eleTree/eleTree"
}).extend({
    treetable: "treetable-lay/treetable"
}).use(['element', 'form', 'eleTree', 'layer', 'jquery', 'table', 'laydate', 'treetable'], function () {
    var element = layui.element;
    var form = layui.form,
        layer = layui.layer,
        laypage = layui.laypage,
        $ = layui.jquery,
        table = layui.table,
        eleTree = layui.eleTree,
        treetable = layui.treetable,
        laydate = layui.laydate;

    var roleId = undefined;
    var roleCode = undefined;

    function reload(){
        treetable.render({
            treeColIndex: 1,
            treeSpid: -1,
            treeIdName: 'id',
            treePidName: 'pid',
            treeDefaultClose: false,
            treeLinkage: false,
            elem: '#roleTable',
            url: '/permission/roleList',
            page: false,
            height: 'full-30',
            cols: [[
                {type: 'radio', width: "5%"}
                ,{field: 'roleCode', title: '角色代码'}
                ,{field: 'roleName', title: '角色名称'}
            ]],
            defaultToolbar: [],
            toolbar: '#tableToolbar'
        });
    }
    reload();
    $("#search").click(function () {
        var roleCode = $("#roleCode").val();
        table.reload('roleTable', {
            where: {
                searchCode: roleCode
            }
            , page: {
                curr: 1
            }
        });
    });

    var treeParams = {
        elem: '.permissionTree',
        //data: data,
        url: "/permission/menuList",
        method: "post",
        contextmenuList: ["add", "edit", "remove"],
        renderAfterExpand: true,
        expandOnClickNode: false,
        showCheckbox: true,
        defaultExpandAll: true,
        highlightCurrent: true,
        contentType: 'application/x-www-form-urlencoded'
    }

    var el = eleTree.render(treeParams);

    $(".sumbitPermission").click(function () {
        if (roleId == undefined) {
            layer.msg("请先选择赋予权限的角色！");
            return;
        }
        top.layer.confirm('确认给该角色赋予勾选权限?', {icon: 3, title: '提示'}, function (index) {
            var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
            var ids = new Array();
            $.each(el.getChecked(false, true), function (index, e) {
                ids.push(e.id);
            });
            $.post('/permission/comfire_permission', {
                roleId: roleId,
                permissionIds: JSON.stringify(ids)
            }, function (d) {
                if (d.code == '200') {
                    top.layer.msg("赋权成功", {icon: 1});
                    treeParams.where = {roleId: roleId};
                    el = eleTree.render(treeParams);
                } else {
                    top.layer.msg("赋权失败," + d.msg, {icon: 2});
                }
                top.layer.close(shadeIndex);
            }, 'json');
        });
    });

    //单击行选中radio及加载permission信息
    table.on('row(roleTable)', function (obj) {
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');//选中行样式
        obj.tr.find('input[lay-type="layTableRadio"]').prop("checked", true);
        form.render('radio');
        treeParams.where = {roleId: obj.data.id};
        roleId = obj.data.id;
        roleCode = obj.data.roleCode;
        el = eleTree.render(treeParams);
    });

    table.on('toolbar(roleTable)', function (obj) {
        var tableCheckData = table.checkStatus(obj.config.id).data;
        switch (obj.event) {
            case 'add':
                var index = layer.open({
                    type: 2
                    , title: "新增"
                    , maxmin: true
                    , area: ['30%', '50%']
                    , content: 'permission/addHtml?id=' + roleId
                    , btn: ['保存', '返回']
                    , yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);

                        var roleCode = body.find("#roleCode").val();
                        var roleName = body.find("#roleName").val();

                        if (roleCode == '') {
                            top.layer.msg("角色编码不能为空");
                            return;
                        }
                        if (roleName == '') {
                            top.layer.msg("角色名称不能为空");
                            return;
                        }

                        var addData = {
                            roleCode: roleCode,
                            roleName: roleName,
                            pid: roleId
                        }
                        var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                        $.post('/permission/addRole', addData, function (d) {
                            if (d.code == '200') {
                                top.layer.msg("新增成功", {icon: 1});
                                layer.close(index);
                                roleId = undefined;
                                reload();
                            } else {
                                top.layer.msg("新增失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                        }, 'json');
                    }
                });
                break;
            case 'edit':
                if (roleId == undefined) {
                    layer.msg("请先选择修改数据！");
                    return;
                }
                var index = layer.open({
                    type: 2
                    , title: "修改"
                    , maxmin: true
                    , area: ['30%', '50%']
                    , content: 'permission/editHtml?id=' + roleId
                    , btn: ['保存', '返回']
                    , yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);

                        var roleCode = body.find("#roleCode").val();
                        var roleName = body.find("#roleName").val();

                        if (roleCode == '') {
                            top.layer.msg("角色编码不能为空");
                            return;
                        }
                        if (roleName == '') {
                            top.layer.msg("角色名称不能为空");
                            return;
                        }

                        var addData = {
                            id: roleId,
                            roleCode: roleCode,
                            roleName: roleName
                        }
                        var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                        $.post('/permission/editRole', addData, function (d) {
                            if (d.code == '200') {
                                top.layer.msg("修改成功", {icon: 1});
                                layer.close(index);
                                roleId = undefined;
                                reload();
                            } else {
                                top.layer.msg("修改失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                        }, 'json');
                    }
                });
                break;
            case 'del':
                if (roleId == undefined) {
                    layer.msg("请先选择删除数据！");
                    return;
                }
                if (roleCode == 'system') {
                    top.layer.msg("system角色不能删除");
                    return;
                }
                top.layer.confirm('是否删除?', {icon: 3, title: '提示'}, function (index) {
                    $.post('/permission/deleteRole', {id: roleId}, function (d) {
                        if (d.code == '200') {
                            top.layer.msg("删除成功", {icon: 1});
                            layer.close(index);
                            roleId = undefined;
                            reload();
                        } else {
                            top.layer.msg("删除失败," + d.msg, {icon: 2});
                        }
                    }, 'json');
                });
                break;
        }
    });
})

function loadTree(data) {
    var setting = {
        check: {
            enable: true,
            chkStyle: "checkbox"//显示 checkbox 选择框，默认checkbox可选择值radio
        }
        , data: {
            simpleData: {
                enable: true
            }
        }
        , callback: {
            onCheck: zTreeOnCheck
        }
    };
    var zTreeNodes = data;
    var city = $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
}

function zTreeOnCheck(event, treeId, treeNode) {
    alert("id=" + treeNode.id + ",name=" + treeNode.name + ",pid=" + treeNode.pId);//弹出城市名字
}